package com.api.util.repo;

import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;

public class PropertiesAppender {

	private Properties properties;

	private final String propertiesFile;

	public PropertiesAppender(String propertiesFile) {

		if (propertiesFile == null) {
			throw new IllegalArgumentException("Properties file cannot be null");
		}
		this.propertiesFile = propertiesFile;
		this.properties = readPropertiesFile();
	}

	public String getProperty(String property) {
		if (!properties.containsKey(property)) {
			throw new IllegalArgumentException(String.format("Property '%s' not found in file '%s'", property, propertiesFile));
		}
		return properties.getProperty(property);
	}

	public Map<String, String> getProperties(String property) {
		Map<String, String> map = new HashMap<String, String>();
		for (Entry<Object, Object> entry : properties.entrySet()) {
			String keyName = String.valueOf(entry.getKey());
			if (keyName.startsWith(property)) {
				String value = properties.getProperty(keyName);
				map.put(keyName, value);
			}
		}
		return map;
	}

	public void appendProperty(String property, String value) {
		Map<String, String> map = new HashMap<String, String>();
		map.put(property, value);
		appendProperties(map);
	}

	public void appendProperties(Map<String, String> properties) {
		if (!properties.isEmpty()) {

			try {
				FileWriter fstream = new FileWriter(propertiesFile, true);
				BufferedWriter fbw = new BufferedWriter(fstream);
				fbw.newLine();
				for (Entry<String, String> property : properties.entrySet()) {
					if (this.properties.containsKey(property.getKey())) {
						throw new IllegalStateException(String.format("Property '%s' already exists", property.getKey()));
					}
					fbw.write(property.getKey() + "=" + property.getValue());
					fbw.newLine();
				}
				fbw.close();
				this.properties = readPropertiesFile();

			} catch (Exception e) {
				throw new IllegalStateException(String.format("Couldn't save properties in file %s", propertiesFile), e);
			}
		}
	}

	private Properties readPropertiesFile() {
		Properties props = new Properties();
		try {
			props.load(new FileInputStream(propertiesFile));
		} catch (FileNotFoundException e) {

		} catch (IOException e) {
			throw new IllegalStateException(String.format("Couldn't load properties file %s", propertiesFile), e);
		}
		return props;
	}
}
